package com.defysoft.waukids.attend;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.R;

public class Attend_Update_Insert_A extends BaseActivity implements
		OnCheckedChangeListener, OnClickListener {
	EditText editText;
	TextView tv;
	TextView okbtn;
	RadioGroup radioGroup;
	Toolbar toolbar;
	String stu_code;
	String stu_name;
	String date;
	String att_reason = null;
	String att_check = null;
	int btncheck = 0;

	final int FAIR_UPDATE_EDIT = 9;
	final int SUCCESS_UPDATE_EDIT = 10;
	
	WebView wv;
	String photo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_attend__update__insert_);
		setStartData();

	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		photo = getIntent().getStringExtra("photo");
		stu_code = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_PK_STU_CODE);
		stu_name = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_STU_NAME);
		date = getIntent().getStringExtra(INTENT_EXTRA_ATTEND_DATE);
		okbtn = (TextView) findViewById(R.id.ATTENDEDITINSER_OK);
		okbtn.setOnClickListener(this);
		tv = (TextView) findViewById(R.id.ATTENDEDITINSER_NAME);
		tv.setText(stu_name + "의 출석부");
		editText = (EditText) findViewById(R.id.ATTENDEDITINSER_ATTTV);
		wv=(WebView)findViewById(R.id.ATTENDEDITINSER_IMG);
		wv.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startActivity( new Intent(Attend_Update_Insert_A.this, Attend_SelectDay_Photo_A.class)
					.putExtra("photo",photo));
					break;
				}
				return false;
			}
		});
		wv.setVerticalScrollBarEnabled(false);
		wv.setVerticalScrollbarOverlay(false);
		wv.setHorizontalScrollBarEnabled(false);
		wv.setHorizontalScrollbarOverlay(false);
		wv.setInitialScale(100);

		if ( photo == null||photo.length()<5) {// 이미지 파일이 없으면 앱내에서 지정된 이미지를 뿌려주고
			wv.setBackgroundColor(0);
			wv.setBackgroundResource(R.drawable.perm_group_personal_info);
		} else {// 이미지 파일이 있으면
			wv.loadDataWithBaseURL(null,
					creHtmlBody(photo), "text/html", "utf-8", null);
		}
		
		
		toolbar = (Toolbar) findViewById(R.id.ATTENDEDITINSER_TOOL);
		radioGroup = (RadioGroup) findViewById(R.id.ATTENDEDITINSER_RADIO);
		radioGroup.setOnCheckedChangeListener(this);

		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		try {
			att_reason = getIntent().getStringExtra(
					INTENT_EXTRA_ATTEND_ATT_REASON);
			att_check = getIntent().getStringExtra(
					INTENT_EXTRA_ATTEND_ATT_CHECK);
		} catch (Exception e) {
			att_reason = null;
			att_check = null;
		}
		if (att_reason != null) {
			editText.setText(att_reason);
		}
		if (att_check != null) {
			if (att_check.equals("0")) {
				radioGroup.check(R.id.ATTENDEDITINSER_RADIO1);
			} else {
				radioGroup.check(R.id.ATTENDEDITINSER_RADIO2);
			}
		}
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				mainThread(cho);
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // 0번은 꼭 try catch의 오류수정코드
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG)
					.show();
			break;
		case FAIR_UPDATE_EDIT: // 1번은 꼭 서버에러코드 출력으로
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			showPopup("데이터 갱신실패", (String) _message.obj, 0);
			break;
		case SUCCESS_UPDATE_EDIT:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			setResult(ATTEND_SELECTDAY_DETAIL_UPDATE_INSERT);
			finish();

			break;
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.ATTENDEDITINSER_RADIO1:
			editText.setVisibility(View.INVISIBLE);
			btncheck = 0;
			break;
		case R.id.ATTENDEDITINSER_RADIO2:
			editText.setVisibility(View.VISIBLE);
			btncheck = 1;
			break;
		}
	}

	@Override
	public void onClick(View v) {
		if (att_check == null) {
			startNetwork(2);
		} else {
			startNetwork(1);
		}
	}

	public void mainThread(int a) {
		String msg = "";
		try {
			JSONObject jsonObject;
			if (a == 1) {
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SELECT_ATTEND_UPDATE_EDIT, "Stu_Code=" + stu_code
								+ "&att_date=" + date + "&att_check="
								+ btncheck + "&att_reason="
								+ editText.getText().toString()));
			} else {
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SELECT_ATTEND_INSERT_EDIT, "Stu_Code=" + stu_code
								+ "&att_date=" + date + "&att_check="
								+ btncheck + "&att_reason="
								+ editText.getText().toString()));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(SUCCESS_UPDATE_EDIT, msg);
			} else {
				onNetworkCallback(FAIR_UPDATE_EDIT,
						jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}
	public String creHtmlBody(String imagUrl) {
		StringBuffer sb = new StringBuffer("<HTML>");
		sb.append("<HEAD>");
		sb.append("</HEAD>");
		sb.append("<BODY  style='margin: 0; padding: 0'>");
		sb.append("<img width=\"100%\" height=\"100%\" src=\"" + imagUrl
				+ "\">");
		sb.append("</BODY>");
		sb.append("</HTML>");

		return sb.toString();
	}
}
